package main

import (
	"MaterialIdentification/svc"
	"github.com/gin-gonic/gin"
	"log/slog"
	"net/http"
	"time"
)

type material struct {
	Type     string
	Name     string
	Num      int
	Lasttime time.Time
}

func Getmaterial(context *gin.Context) {
	q := Querydto{}
	context.BindJSON(&q)

	var materials []material
	if q.Condition == "" && q.Start.IsZero() && q.End.IsZero() {
		err := svc.Db.Find(&materials).Error
		if err != nil {
			slog.Error("数据库boom了", "err", err)
			context.JSON(http.StatusOK, NewResp(1, "系统异常"))
			return
		}
		context.JSON(http.StatusOK, NewRespData("无条件查询所有材料信息成功", materials))
		return
	} else if q.Condition != "" && q.Start.IsZero() && q.End.IsZero() {
		err := svc.Db.Where("type LIKE ? OR name LIKE ? OR num LIKE ?", "%"+q.Condition+"%", "%"+q.Condition+"%", "%"+q.Condition+"%").Find(&materials).Error
		if err != nil {
			slog.Error("数据库boom了", "err", err)
			context.JSON(http.StatusOK, NewResp(1, "系统异常"))
			return
		}
		context.JSON(http.StatusOK, NewRespData("只按搜索框查询材料信息成功", materials))
		return
	} else if q.Condition == "" && !q.Start.IsZero() && !q.End.IsZero() {
		err := svc.Db.Where("lasttime BETWEEN ? AND ?", q.Start, q.End).Find(&materials).Error
		if err != nil {
			slog.Error("数据库boom了", "err", err)
			context.JSON(http.StatusOK, NewResp(1, "系统异常"))
			return
		}
		context.JSON(http.StatusOK, NewRespData("只按时间查材料信息成功", materials))
		return
	} else if q.Condition != "" && !q.Start.IsZero() && !q.End.IsZero() {
		err := svc.Db.Where("type LIKE ? OR name LIKE ? OR num LIKE ? OR lasttime BETWEEN ? AND ?", "%"+q.Condition+"%", "%"+q.Condition+"%", "%"+q.Condition+"%", q.Start, q.End).Find(&materials).Error
		if err != nil {
			slog.Error("数据库boom了", "err", err)
			context.JSON(http.StatusOK, NewResp(1, "系统异常"))
			return
		}
		context.JSON(http.StatusOK, NewRespData("综合查询材料信息成功", materials))
		return
	}
}
